//    Copyright (C) Kherty.  All rights reserved.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using OpenLS.Spreadsheet.Formats.Biff.Records;

namespace OpenLS.Spreadsheet.Formats.Biff
{

    internal sealed class BiffRecordReader
    {
        private readonly long _length;
        private readonly BiffReaderContext _context;
        private List<BiffRecord> _allRecords;
        private int _index = -1;

        public BiffRecordReader(BiffReaderContext context)
        {
            _context = context;
            _length = context.BaseStream.Length;
        }

        private BiffRecord readRawRecord()
        {
            if (_length == _context.BaseStream.Position)
                return null;
            BiffRecordType biffType;
            try
            {
                biffType = (BiffRecordType) _context.ReadUInt16();
            }
            catch
            {
                return null;
            }
#if DEBUG
            BiffRecordFactory.Test();
#endif
            BiffRecord record = BiffRecordFactory.NewRecord(biffType);
          //\\  Debug.WriteLine(record.RecordType);
            record.Read(_context);
            return record;
        }

        internal IEnumerable<BiffRecord> getAllRecords()
        {
            BiffRecord previousRecord = null;
            BiffRecord record = readRawRecord();
            while (record != null)
            {
                if (previousRecord != null)
                    previousRecord.Next = record;
                yield return record;
                previousRecord = record;
                record = readRawRecord();
            }
        }

        internal List<BiffRecord> getAllRecords2()
        {
            var records = new List<BiffRecord>(getAllRecords());
            foreach (BiffRecord item in records)
            {
                    item.ReadWithContinue();
            }
            return records;
        }

        public BiffRecord ReadRecord()
        {
            if (_allRecords == null)
                _allRecords = getAllRecords2();
            _index++;
            if (_index < _allRecords.Count)
                return _allRecords[_index];
            return null;
        }
        public IEnumerable<BiffRecord> GetRecords()
        {
            BiffRecord toYield = ReadRecord();
            while (toYield != null)
            {
                yield return toYield;
                toYield = ReadRecord();
            }
            _index = -1;
        }
    }
}